// 运行时配置

import { RequestConfig, RunTimeLayoutConfig, history } from '@umijs/max';
import { message } from 'antd';
import { userMe } from './services/home';
import { logout } from './services/login';

import ICON from '@/assets/icon.png';

import { setupGlobalErrorHandling } from './utils/setupGlobalErrorHandling';

// 处理一些无关紧要的控制信息
setupGlobalErrorHandling();

// 全局初始化数据配置，用于 Layout 用户信息和权限初始化
// 更多信息见文档：https://umijs.org/docs/api/runtime-config#getinitialstate
export async function getInitialState() {
  if (history.location.pathname === '/login') return {};
  const result = await userMe();
  return {
    name: result,
    avatar: ICON,
  };
}

export const layout: RunTimeLayoutConfig = () => {
  return {
    logo: ICON,
    menu: {
      locale: false,
      defaultOpenAll: true,
    },
    layout: 'mix',
    logout: async () => {
      const result = await logout();
      console.log(result);
      message.success('退出成功');
      history.push('/login');
    },
  };
};

export const request: RequestConfig = {
  timeout: 3000,
  // baseURL: 'http://18.143.79.247:9998',
  withCredentials: true,
  httpsAgent: {
    rejectUnauthorized: false,
  },
  errorConfig: {
    errorHandler() {},
    errorThrower() {},
  },
  requestInterceptors: [
    (url, options) => {
      url = process.env.NODE_ENV === 'development' ? '/api' + url : url;
      return { url, options };
    },
  ],
  responseInterceptors: [
    // 一个二元组，第一个元素是 request 拦截器，第二个元素是错误处理
    [
      (response) => {
        const { data = {} as any, config } = response;

        return response;
      },
      (error: any) => {
        const { response } = error;
        console.log(response);

        const status = response?.status;

        // switch (status) {
        //   case 401:
        //     if (history.location.pathname === '/login') {
        //       message.error('账号密码错误，请重试！');
        //       break;
        //     }
        //     message.error('登录状态已过期，请重新登录');
        //     history.push('/login');
        //     break;
        //   case 400:
        //     message.error(response.data);
        //     break;
        //   default:
        //     message.error(error.message);
        //     break;
        // }

        return Promise.reject(error);
      },
    ],
  ],
};
